package com.chixing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.Customer;
import com.chixing.mapper.CustomerMapper;
import com.chixing.service.AddCustomerService;
import com.chixing.service.ex.CustomerNotFindException;
import com.chixing.service.ex.SaveException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.concurrent.TimeUnit;

@Service
public class AddCustomerServiceImpl implements AddCustomerService {
    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Customer getById(Integer custId) {
        String key = "cust_" + custId;
        ValueOperations<String, Customer> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            Object object = operations.get(key);
            Customer customer = JSON.parseObject(JSON.toJSONString(object),Customer.class);
            System.out.println("从缓存中获取用户ID" + customer.getCustId() + "的数据");
            return customer;
        } else {
            Customer data = customerMapper.selectById(custId);
            if (data == null) {
                throw new CustomerNotFindException("用户数据异常");
            }
            System.out.println("从数据库中获取用户ID" + data.getCustId() + "的数据");
            operations.set(key, data, 5, TimeUnit.HOURS);
            return data;

        }
    }


    @Override
    public Integer updateCust(Integer custId, Customer customer) {
        ValueOperations<String, Customer> operations = redisTemplate.opsForValue();
        Integer result = customerMapper.updateCust(custId, customer);
        System.out.println("修改的行数为" + result);
        if (result != 1) {
            throw new SaveException("数据异常,修改信息失败");
        } else {
            String key = "cust_" + custId;
            boolean haskey = redisTemplate.hasKey(key);
            if (haskey) {
                redisTemplate.delete(key);
                System.out.println("删除缓存中的key-----------> " + key);
                Customer custNew = customerMapper.selectById(custId);
                if (custNew != null) {
                    operations.set(key, custNew, 3, TimeUnit.HOURS);
                } else throw new CustomerNotFindException("用户数据异常,缓存失败");

            }
            Customer custNew = customerMapper.selectById(custId);
            System.out.println("从数据库获取新的数据" + custNew);
            operations.set(key, custNew, 3, TimeUnit.HOURS);
            return result;
        }
    }
}




